package com.webtest.tag;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.JspTag;
import javax.servlet.jsp.tagext.SimpleTag;
import java.io.IOException;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/8/9 15:52
 */
public class HelloSimpleTag implements SimpleTag {
    private static final Logger LOGGER = LoggerFactory.getLogger(HelloSimpleTag.class);
    private PageContext pageContext;

    private String value;
    private String count;

    public void setValue(String value) {
        this.value = value;
    }

    public void setCount(String count) {
        this.count = count;
    }

    // 标签体逻辑实际应该编写到该方法中
    @Override
    public void doTag() throws JspException, IOException {
        LOGGER.info("doTag");
        HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
        pageContext.getOut().print("hello " + request.getParameter("name"));
        LOGGER.info("value:" + value);
        LOGGER.info("count:" + count);

        JspWriter writer = pageContext.getOut();

        int c = Integer.parseInt(count);
        for (int i = 0; i < c; i++) {
            writer.print("<br/>");
            writer.print(i + " " + value);
        }
    }

    @Override
    public JspTag getParent() {
        LOGGER.info("getParent");
        return null;
    }

    @Override
    public void setParent(JspTag jspTag) {
        LOGGER.info("setParent");
    }

    // JSP引擎调用，把代表JSP页面的PageContext对象传入
    // PageContext可以获取JSP页面的其他8个隐含对象
    // 凡是JSP页面可以做的标签都可以完成
    @Override
    public void setJspContext(JspContext jspContext) {
        LOGGER.info("setJspContext");
        LOGGER.info(String.valueOf(jspContext instanceof PageContext));
        this.pageContext = (PageContext) jspContext;
    }

    @Override
    public void setJspBody(JspFragment jspFragment) {
        LOGGER.info("setJspContext");
    }
}
